package com.zt.chatgpt.domain.security.service;

import com.zt.chatgpt.domain.security.model.vo.JwtToken;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: zt
 * @Description: 自定义过滤器，拦截所有携带Token的请求
 * @create: 2024-05-08 23:38
 */

public class JwtFilter extends AccessControlFilter {

    private Logger logger = LoggerFactory.getLogger(JwtFilter.class);

    /**
     * 判断是否携带有效的 JwtToken, 直接返回false，代表访问被拒绝，走下一个流程，即onAccessDenied方法
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    /**
     * 验证Token是否有效
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 约定jwt放入请求参数中
        JwtToken jwtToken = new JwtToken(request.getParameter("token"));
        try {
            // 获取当前请求的主体（用户），验证Token
            getSubject(servletRequest, servletResponse).login(jwtToken);
            return true;
        } catch (Exception e) {
            logger.error("鉴权失败");
            onLoginFail(servletResponse);
            return false;
        }
    }


    private void onLoginFail(ServletResponse servletResponse) throws IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("鉴权失败");
    }
}
